package br.com.comunications.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Utils {
	
	
	/**
	 * Transforma um objeto em um array de bytes
	 * @param obj
	 * @return
	 */
	public static byte[] ObjectForByteArray (Object obj)
	{
	  byte[] bytes = null;
	  ByteArrayOutputStream bos = new ByteArrayOutputStream();
	  try {
	    ObjectOutputStream oos = new ObjectOutputStream(bos); 
	    oos.writeObject(obj);
	    oos.flush(); 
	    oos.close(); 
	    bos.close();
	    bytes = bos.toByteArray ();
	  }
	  catch (IOException ex) {
		  ex.printStackTrace();
	  }
	  return bytes;
	}
	
	/**
	 * Transforma um array de bytes em objeto
	 * @param bytes
	 * @return
	 */
	public static Object ByteArrayForObject (byte[] bytes)
	{
	  Object obj = null;
	  try {
	    ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
	    ObjectInputStream ois = new ObjectInputStream (bis);
	    obj = ois.readObject();
	  }
	  catch (IOException ex) {
		  ex.printStackTrace();
	  }
	  catch (ClassNotFoundException ex) {
		  ex.printStackTrace();
	  }
	  return obj;
	}
	
}
